import moment from 'moment'
import shell from 'shelljs'

const path = require('path')
const fs = require('fs')

let gitPathRoot = ''

export default {
    setPath(path) {
        if (path !== gitPathRoot) {
            gitPathRoot = path
        }
    },
    async status() {
       let status = await appGit.status()
        console.log(status)
    },
    async createGitProject(cloneUrl) {
        // const res = await appGit.init(false)
        // 创建一个临时目录
        const tmp = gitPathRoot + '/tmp'
        console.log('tmp:' + tmp)
        fs.mkdirSync(tmp)
        await appGit.clone(cloneUrl, tmp)
        shell.mv('-f', tmp + '/.git', gitPathRoot)
        shell.rm('-Rf', tmp)
        appGit.raw('reset --hard HEAD')
        return true
    },
    async getUnCommitFiles() {
        // eslint-disable-next-line no-debugger
        // debugger
        console.log(gitPathRoot)
        const status = await appGit.status()
        let tempFiles = []
        let types = ['not_added', 'created', 'deleted', 'modified', 'renamed']
        // let types = ['not_added', 'created', 'modified', 'renamed']
        for (let type of types) {
            status[type].forEach((file) => {
                tempFiles.push({type: type, path: file})
            })
        }
        // keys.forEach((key) => {
        //     tempFiles = tempFiles.concat(status[key])
        // })
        // let files = [...new Set(tempFiles)]
        // files = this.format(files, gitPathRoot + '/')
        return this.format(tempFiles, gitPathRoot)
    },

    /**
     * 格式化文件信息
     * @param files
     * @param root
     * @returns {*[]}
     */
    format(files, root = '') {
        console.log('rootpath:' + root)
        console.log(files)

        if (typeof files !== 'object') {
            files = [files]
        }

        for (let key in files) {
            const file = files[key]
            const fName = file.path.replace(/"/g,"")
            const filePath = root + '/' + fName
            let time = 0
            if (file.type !== 'deleted') {
                const fileInfo = fs.statSync(filePath)
                console.log(fileInfo)
                time = moment(fileInfo.mtimeMs).format('YY-MM-DD hh:mm:ss')
            }

            files[key].path = filePath
            files[key].name = fName
            files[key].time = time
            files[key].ext = path.extname(filePath).substr(1)
        }

        return files
    }
}
